import pygame
import sys
import time
from cat import Cat

RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREY = (128, 128, 128)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

WIDTH = 1050
HEIGHT = 800
GRID_WIDTH = 100
GRID_HEIGHT = 100
RADIUS = 40
PADDING = 50

board = []
for i in range(HEIGHT // GRID_HEIGHT):
    t = []
    for j in range(WIDTH // GRID_WIDTH):
        t.append(0)

    board.append(t)

board[5][5] = 1
board[7][3] = 1
board[1][1] = 1
board[0][7] = 1
board[2][6] = 1
board[2][4] = 1
board[7][5] = 1
board[7][7] = 1
board[5][0] = 1
board[5][9] = 1

cat = Cat(4, 4, board)

pygame.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Catch The Cat")

def draw_board():
    screen.fill(BLACK);
    for (i, row) in enumerate(board):
        padding = 0
        if (i & 1 == 1):
            padding = PADDING

        for (j, e) in enumerate(row):
            if e == 0:
                color = WHITE
            else:
                color = RED

            pygame.draw.circle(screen, color, 
                (padding + j * GRID_WIDTH + GRID_WIDTH // 2, GRID_HEIGHT // 2 + i * GRID_HEIGHT),
                RADIUS, 0)

    cat.draw(screen, BLUE, PADDING, GRID_WIDTH, GRID_HEIGHT, RADIUS)

    pygame.display.update()


def click_board(pos):
    x = pos[0]
    y = pos[1]
    row = y // GRID_HEIGHT
    
    if (row & 1 == 1):
        line = (x - PADDING) // GRID_WIDTH
    else:
        line = x // GRID_WIDTH

    cy = GRID_HEIGHT * row + GRID_HEIGHT // 2
    cx = GRID_WIDTH * line + GRID_WIDTH // 2 + (PADDING if row & 1 == 1 else 0)

    if ((cx - x) * (cx - x) + (cy - y) * (cy - y) <= RADIUS * RADIUS):
        board[row][line] = 1

    path = cat.next_step()
    if path:
        if (len(path) < 3):
            print("You Lose!")
        else:
            cat.set_pos(path[-3])
    else:
        print("You Win!")

    draw_board()

draw_board()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            #print(f"click pos: {event.pos}")
            click_board(event.pos)

    # current_mouse_position = pygame.mouse.get_pos()

    time.sleep(0.016)

